import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:kkhousekeep/models/pick_picture.dart';
import 'package:kkhousekeep/net/upload_connect.dart';
import 'package:kkhousekeep/page/public/take_picture_screen.dart';
import 'package:kkhousekeep/tools/log.dart';
import 'package:kkhousekeep/tools/toast_util.dart';
import 'package:local_image_provider/local_image_provider.dart';

import '../../net/respnse_code.dart';
import '../../tools/dialog_util.dart';

class TakePictureScreenController extends GetxController {
  final List<String>? imagePathList;

  final PhotoPathCallBack? photoPathCallBack;

  TakePictureScreenController(
      {this.imagePathList,
      this.photoPathCallBack,
      this.isUserGalleryOnly = true});

  ///是否为后置摄像头
  var isRearCamera = true.obs;

  ///组件恢复key
  var resumedKey = true.obs;

  ///照相机控制器
  late CameraController cameraController;

  ///本地图片提高器
  late LocalImageProvider imageProvider;

  ///是否只使用相册
  final bool isUserGalleryOnly;

  ///是否有权限
  late bool hasPermission;
  late List<LocalImage> imageList;
  late LocalImage latestImage;
  late DeviceImage deviceImage;
  late ImagePicker imagePicker;
  late XFile? image;
  late UploadImageConnect connect;
  int count = 0;

  @override
  void onInit() {
    super.onInit();
    imagePicker = ImagePicker();
    imageProvider = LocalImageProvider();
    connect = Get.put(UploadImageConnect());
  }

  @override
  onClose() {
    if (!isUserGalleryOnly) {
      cameraController.dispose();
    }
    super.onClose();
  }

  // //todo 尝试使用once
  initImage() async {
    var cameras = await availableCameras();
    var camera = isRearCamera.value ? cameras.first : cameras.last;
    cameraController = CameraController(
      camera,
      ResolutionPreset.medium,
    );
    await cameraController.initialize();
    hasPermission = await imageProvider.initialize();
    imageList = await imageProvider.findLatest(1);
    latestImage = imageList.first;
  }

  ///打开相册
  Future<void> pickPicture() async {
    image = await imagePicker.pickImage(source: ImageSource.gallery);
    if (image == null) return;
    await Get.to(() => DisplayPictureScreen(
          imagePath: image?.path ?? "",
          takePictureScreenController: this,
        ));
  }

  ///拍照
  Future<void> takePicture(CameraController cameraController) async {
    try {
      var photo = await cameraController.takePicture();
      await Get.to(
        () => DisplayPictureScreen(
          imagePath: photo.path,
          takePictureScreenController: this,
        ),
      );
    } catch (e) {
      logE(e.toString());
    }
  }

  ///更换摄像头
  void changeIsRearCamera() {
    isRearCamera.value = !isRearCamera.value;
  }

  ///上传图片
  void uploadImage(String imagePath) async {
    if (!checkIsImageExpectGif(imagePath)) {
      ToastUtils.showToast(tip: "请上传除gif以外的图片");
      return;
    }
    final tmpDir = (await getTemporaryDirectory()).path;
    final targetPath = '$tmpDir/${DateTime.now().millisecondsSinceEpoch}.jpg';
    DialogUtil.showNetworkLoading(msg: "上传中");
    var result = await FlutterImageCompress.compressAndGetFile(
      imagePath,
      targetPath,
    );
    var response = await connect.uploadImage(result?.path ?? "");
    DialogUtil.dismiss();
    if (response == null) {
      return;
    }
    if (response.code != ResponseCode.success) {
      DialogUtil.showNetworkFail();
      return;
    }
    String netPath = response.data;
    photoPathCallBack?.call(PickPictureModel(imagePath, netPath)) ??
        imagePathList?.add(imagePath);
    if (!isUserGalleryOnly) {
      Get.back();
    }
    Get.back();
  }

  bool checkIsImageExpectGif(String imagePath) {
    var ext = imagePath.toLowerCase();
    return ext.endsWith(".jpg") ||
        ext.endsWith(".jpeg") ||
        ext.endsWith(".png") ||
        ext.endsWith(".bmp");
  }

  void remakePhoto(String imagePath) async {
    var file = File(imagePath);
    await file.delete();
    Get.back();
  }

  Future<Directory> getTemporaryDirectory() async {
    return Directory.systemTemp;
  }
}
